import Table from "@/components/Table";
import { Space, Button, message, Modal, Form, Input, FormInstance, Tag, Radio, RadioChangeEvent } from "antd";
import '@/assets/styles/buttonStyles.css';
import '@/views/system/user/user.css';
import { DataType, ColumnsType } from "@/types/right";
import { useEffect, useState } from "react";
import { getCookie } from "@/utils/cookies";
import React from "react";
import { useNavigate } from "react-router-dom";
import baseUrl from '@/config';
import LoadingIndicator from '@/components/loading';

const Right: React.FC = () => {
  const [pageLoading, setPageLoading] = useState(true);
  const [data, setData] = useState<DataType[]>([]);
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selInfo, setSelInfo] = useState('');
  const [selInfo2, setSelInfo2] = useState('');
  const [listNum, setListNum] = useState(0);
  const [editId, setEditId] = useState(0);
  const [editInfo, setEditInfo] = useState('');

  const showModalEdit = (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setEditId(record.id);
      setIsModalOpen(true);
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };


  const navigateTo = useNavigate();
  useEffect(() => {
    // 判断是否有token，检测用户是否已登录，如果未登录，给出提示，并将其跳转到登录页
    if (getCookie('token') == null) {
      message.error("尚未登录，不得访问！", 1);
      navigateTo("/login");
      return;
    }
    // if (localStorageGetItem('userName') !== 'root') {
    //   message.error("您非root超级管理员，无权访问！", 1);
    //   navigateTo("/");
    //   return;
    // }
    fetchData(); // 调用获取数据的函数
  }, []);


  const fetchData = async () => {
    try {
      const response = await fetch(baseUrl + '/sys/system/getSysRoleList', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.msg === '操作成功') {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  // 定义按钮点击事件处理函数
  const handleModifyScore = async () => {
    // 处理修改逻辑
    try {
      const response = await fetch(baseUrl + '/sys/system/updateRoleRightById', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
        body: JSON.stringify({
          id: editId,
          userSource: null,
          userKey: null,
          userType: null,
          userRight: editInfo,
          createTime: null,
          updataTime: null,
          isDeletd: 0
        })
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          message.success(data.msg, 1);
          fetchData();
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
    setIsModalOpen(false);
  };



  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "用户来源",
      dataIndex: "userSource",
      key: "userSource",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === 'behind') {
          return <Tag color="blue">react后台管理系统</Tag>;
        } else if (text === 'front') {
          return <Tag color="green">WeChat前台小程序</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag>未知</Tag>;
        }
      }
    },
    {
      title: "用户标识",
      dataIndex: "userKey",
      key: "userKey",
    },
    {
      title: "用户类型",
      dataIndex: "userType",
      key: "userType",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === '管理员') {
          return <Tag color="blue">管理员</Tag>;
        } else if (text === '常规用户') {
          return <Tag color="green">常规用户</Tag>;
        } else if (text === '普通用户') {
          return <Tag color="yellow">普通用户</Tag>;
        }
        else if (text === '工作人员') {
          return <Tag color="purple">工作人员</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag>超级管理员</Tag>;
        }
      }
    },
    {
      title: "用户权限",
      dataIndex: "userRight",
      key: "userRight",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === 'look') {
          return <Tag color="blue">仅查看</Tag>;
        } else if (text === 'edit') {
          return <Tag color="green">可编辑</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag>最高权限</Tag>;
        }
      }
    },
    {
      title: "加入时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "最后修改时间",
      key: "updateTime",
      dataIndex: "updateTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="default" onClick={(e) => showModalEdit(record, e)} className="edit-button">
            修改权限
          </Button>
        </Space>
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      className: 'hiddenColumn'
    }
  ];

  const selInfoDetail = async () => {
    try {
      setPageLoading(true);
      const response = await fetch(baseUrl + '/sys/system/getRoleBySth?info=' + selInfo + '&sth=' + selInfo2, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        }
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
          message.success(data.msg, 1);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const SubmitButton = ({ form }: { form: FormInstance }) => {
    const [submittable, setSubmittable] = React.useState(false);

    // Watch all values
    const values = Form.useWatch([], form);

    React.useEffect(() => {
      form.validateFields({ validateOnly: true }).then(
        () => {
          setSubmittable(true);
        },
        () => {
          setSubmittable(false);
        },
      );
    }, [values]);

    return (
      <Button type="primary" htmlType="submit" disabled={!submittable} onClick={selInfoDetail}>
        查询
      </Button>
    );
  };

  const handleSelInfoChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    setSelInfo(event.target.value);
  };

  const handleSelInfo2Change = (e: RadioChangeEvent) => {
    setSelInfo2(e.target.value);
  };

  const handleEditInfoChange = (e: RadioChangeEvent) => {
    setEditInfo(e.target.value);
  };


  return (
    <>
      <LoadingIndicator loading={pageLoading} />
      <Form form={form} name="validateOnly" layout="inline" autoComplete="off">
        <Form.Item>
          <Radio.Group size="middle" value={selInfo2} onChange={handleSelInfo2Change}>
            <Radio.Button value="用户来源">按用户来源查询</Radio.Button>
            <Radio.Button value="用户权限">按用户权限查询</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="name" label="" rules={[{ required: true, message: "查找字段内容不得为空,如不想查找请点击重置!" }]}>
          <Input placeholder="(选择其中一个标准精确查询）" value={selInfo} onChange={handleSelInfoChange} />
        </Form.Item>
        <Form.Item>
          <Space>
            <SubmitButton form={form} />
            <Button htmlType="reset">重置</Button>
          </Space>
        </Form.Item>
        <Tag bordered={true} color="green" className="total-tag">
          共{listNum}条记录
        </Tag>
        <Button type="link" onClick={fetchData}>查询所有</Button>
      </Form>
      <Modal title="请输入要修改的权限（不支持操作超级管理员权限）" open={isModalOpen} okText="确定修改"
        cancelText="取消" onOk={handleModifyScore} onCancel={handleCancel}>
        <Form>
          <Form.Item
            name="1"
            rules={[{ required: true, message: "请选择权限！" }]}
          >
            <Radio.Group size="middle" style={{ width: '350px' }} value={editInfo} onChange={handleEditInfoChange}>
              <Radio.Button value="look">仅查看</Radio.Button>
              <Radio.Button value="edit">可编辑</Radio.Button>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
      <Table<DataType> columns={columns} dataSource={data} />
    </>
  );
};

export default Right;